/**
 * Image Switch
 * Implements jquery UI Dialog for images and videos through AJAX
 * Loads Social Plugins
 *
 * @author Seth
 * @version 1.3
 */
var ImgSw = function() {
	var data = {},
		translate = {},
		paths = {},
		position = 0,
		frame = 0,

		// prevent default
		_pdef = function(e) {
			e.preventDefault();

		// trigger an event when either of imgsw windows are closed
		}, _trigger = function() {
			$("body").trigger({
				type: "ImgSw",
				close: true
			});

		// get prev entity
		},	prev = function(s) {
			var x = s.data[s.pos - 1],
				y = s.data[s.data.length - 1];

			return x ? x : y;

		// get current entity
		},	curr = function(s) {
			return s.data[s.pos];

		// get next entity
		},	next = function(s) {
			var x = s.data[s.pos + 1],
				y = s.data[0];

			return x ? x : y;

		// create picture dialog
		}, _img = function(x, y) {
			// comming from dashboard or hash or detail page
			if(isNaN(x)) {
				// if dashboard, we have data path and url
				var path = x.data('path'),
					url = x.data('url');

				// external ? (dashboard)
				if(y == true) {
					var path = x.data('url'),
						dash = x.closest('div.entry').data('identity').split('|'),
						url = SITE_URL + 'dashboard/view/id/'+ dash[0];
				}

				// x is the file id
				x = x.attr('rel');
			}

			// show loading
			Petolio.showLoading();

			// run the ajax
	    	Petolio.ajax({
				url: 'imgsw/img',
				type: 'post',
				data: {id: x, path: path ? path : paths.image},
				cache: false,
				success: function (x) {
					var d = {data: x.data, pos: x.pos},
						l = [curr(d), next(d), prev(d)];

					// set local cache
					data = {};
					position = x.data[x.pos][1];
					$.each(x.data, function(i, v) {
						data[v[1]] = [v[0], false, v[2]];
					});

					// preload and open dialog
					__preload(l);
					__check(l, function(){
						Petolio.hideLoading();
						__open(x);
					});
				}
			});

			// preload function
			var __preload = function(d) {
				var p = {};

				$.each(d, function(i, v) {
					if(data[v[1]][1] == false) {
						p[i] = new Image();
						p[i].onload = function() {
							data[v[1]][1] = this;
						};
						p[i].src = dash ? SITE_URL + 'imgsw/ext/url/' + Base64.encode(v[1]) : v[1];
					}
				});

			// check if image is preloaded or not
			}, __check = function(x, f) {
				var d = false;

				$.each(x, function(i, v) {
					if(data[v[1]][1] == false) {
						window.setTimeout(function(){
							__check(x, f);
						}, 100);

						d = true;
						return false;
					}
				});

				if(d) return;
				if(f) f.apply(this, Array.prototype.slice.call(arguments, 1));

			// switch between images
			}, __switch = function(identity, a, y) {
				if(data[y][1] == false) {
					if(!$("#dialog-loading").length > 0)
						Petolio.showLoading();

					window.setTimeout(function() {
						__switch(identity, a, y);
					}, 100);

					return false;
				}

				if($("#dialog-loading").length > 0)
					Petolio.hideLoading();

				// update DOM
		        $("#"+ identity).dialog("option", "title", translate.view_picture + ' - '+ translate.progress.replace('%1$s', a.indexOf(y) + 1).replace('%2$s', a.length));
				$('#main_entity').css('width', data[y][1].width).html($(data[y][1]).css({display: 'block'}));

			// handle on gallery click
			}, __click = function(identity, f) {
				var a = [];
				$.each(data, function(i, v){ a.push(i); });

				var x = a.indexOf(position),
					y = ImgSw[f]({data: a, pos: x}),
					k = ImgSw[f]({data: a, pos: a.indexOf(y)}),
					l = [[data[k][0], k]];

				__preload(l);
				__switch(identity, a, y);

				return position = y;

			// handle social
			}, __social = function(identity, d) {
				var x = data[d],
					params = {
						scope: dash ? dash[1] : 'po_files',
						label: dash ? '{ignore}' : '{direct}',
						id: dash ? dash[0] : x[0],
						url: '<a href="'+ ((url ? url : _url()) + (dash ? '' : '#img/'+ x[0])) +'">{'+ (dash ? 'entries' : 'pictures') +'}</a>',
						owner: dash ? dash[2] : x[2]
					};

		        Social.load('comments', $("#"+ identity), params);
		        Social.load('ratings', $("#"+ identity), params);
		        Social.load('subscriptions', $("#"+ identity), params);

			// open dialog
			}, __open = function(x) {
				if(Petolio.stopLoading() == true)
					return true;

				var identity = 'dialog-picture';
		    	$('<div id="'+ identity +'" title="'+ translate.view_picture +'" class="ui-state-highlight">'+
					'<div style="position: relative; margin: 8px 0px 8px 0px; width: 802px; overflow: hidden;">' +
						'<div style="margin: 0 auto 0 auto; border: 1px solid #fff; background: #FFF;" id="main_entity">'+
						'</div>'+
					'</div>'+
					'<div class="social" style="text-align: left; width: 500px; margin: 0 auto; position: relative;">'+
						'<div class="comments"><div style="height: 7px;"></div><div style="text-align: center; padding: 2px 5px; border: 1px solid #A5CC7D; background: #CEECB0;">'+ translate.load_social +'</div><div style="height: 7px;"></div></div>'+
						'<div style="position: absolute; top: 10px; right: 0px;">'+
							'<span class="subscriptions"></span>'+
							'<span class="ratings"></span>'+
						'</div>'+
					'</div>'+
				'</div>').dialog({
					resizable: false,
					modal: true,
					autoOpen: false,
					width: 825,
					position: ['center', 25],
					minHeight: 50,
					buttons: [{
						text: translate.close,
						click: function() {
							$(this).dialog("close");
						}
					}],
					close: function() {
						$("#"+ identity).remove();
						_trigger();
					},
					open: function() {
						// if there's more than 1 picture add gallery functionality
						if(x.total > 1)
			        		gallery(x, identity,
			        			// previous callback
			        			function() {
				        			__social(identity, __click(identity, 'prev'));

								// next callback
				        		}, function() {
				        			__social(identity, __click(identity, 'next'));
				        	});

				        // run by social plugins
						__social(identity, position);
					}
				});

				// update DOM
				$('#main_entity').css('width', data[x.data[x.pos][1]][1].width).append($(data[x.data[x.pos][1]][1]).css({display: 'block'}));
				$("#"+ identity).dialog('open');
			};

		// create audio dialog
		}, _aud = function(x, y) {
			var player = '<link href="/css/jquery.jplayer.css" rel="stylesheet" type="text/css" />'+
				'<div id="jquery_jplayer_1" class="jp-jplayer"></div>'+
				'<div id="jp_container_1" class="jp-audio" style="margin: 0 auto; width: 500px;">'+
					'<div class="jp-type-single">'+
						'<div class="jp-gui jp-interface">'+
							'<ul class="jp-controls">'+
								'<li><a href="javascript:void(0);" class="jp-play" tabindex="1" style="display: block;" title="'+ translate.play +'">'+ translate.play +'</a></li>'+
								'<li><a href="javascript:void(0);" class="jp-pause" tabindex="1" style="display: block;" title="'+ translate.pause +'">'+ translate.pause +'</a></li>'+
								'<li><a href="javascript:void(0);" class="jp-stop" tabindex="1" style="display: block;" title="'+ translate.stop +'">'+ translate.stop +'</a></li>'+
								'<li><a href="javascript:void(0);" class="jp-mute" tabindex="1" style="display: block;" title="'+ translate.mute +'">'+ translate.mute +'</a></li>'+
								'<li><a href="javascript:void(0);" class="jp-unmute" tabindex="1" style="display: block;" title="'+ translate.unmute +'">'+ translate.unmute +'</a></li>'+
								'<li><a href="javascript:void(0);" class="jp-volume-max" tabindex="1" style="display: block;" title="'+ translate.max_volume +'">'+ translate.max_volume +'</a></li>'+
							'</ul>'+
							'<div class="jp-progress">'+
								'<div class="jp-seek-bar">'+
									'<div class="jp-play-bar"></div>'+
								'</div>'+
							'</div>'+
							'<div class="jp-volume-bar">'+
								'<div class="jp-volume-bar-value"></div>'+
							'</div>'+
							'<div class="jp-time-holder">'+
								'<div class="jp-current-time"></div>'+
								'<div class="jp-duration"></div>'+
								'<ul class="jp-toggles">'+
									'<li><a href="javascript:void(0);" class="jp-repeat" tabindex="1" style="display: block;" title="'+ translate.repeat +'">'+ translate.repeat +'</a></li>'+
									'<li><a href="javascript:void(0);" class="jp-repeat-off" tabindex="1" style="display: block;" title="'+ translate.repeat_off +'">'+ translate.repeat_off +'</a></li>'+
								'</ul>'+
							'</div>'+
						'</div>'+
						'<div class="jp-no-solution">'+ translate.update +'</div>'+
					'</div>'+
				'</div>';

			// comming from dashboard or hash or detail page
			if(isNaN(x)) {
				// if dashboard, we have data path and url
				var path = x.data('path'),
					url = x.data('url');

				// external ? (dashboard)
				if(y == true) {
					var path = x.data('url'),
						dash = x.closest('div.entry').data('identity').split('|'),
						url = SITE_URL + 'dashboard/view/id/'+ dash[0];
				}

				// x is the file id
				x = x.attr('rel');
			}

			// show loading
			Petolio.showLoading();

			// run the ajax
	    	Petolio.ajax({
				url: 'imgsw/aud',
				type: 'post',
				data: {id: x, path: path ? path : paths.audio},
				cache: false,
				success: function (x) {
					// set local cache
					data = {};
					position = x.data[x.pos][1];
					$.each(x.data, function(i, v) {
						data[v[1]] = v;
					});

					Petolio.hideLoading();
					__open(x);
				}
			});

	    	// switch between audios
			var __switch = function(identity, a, y) {
				// update DOM
		        $("#"+ identity).dialog("option", "title", translate.view_audio + ' - '+ translate.progress.replace('%1$s', a.indexOf(y) + 1).replace('%2$s', a.length));
		        $('#main_entity').html($(player));
		        __player(data[y][1]);

			// handle on gallery click
			}, __click = function(identity, f) {
				var a = [];
				$.each(data, function(i, v){ a.push(i); });

				var x = a.indexOf(position),
					y = ImgSw[f]({data: a, pos: x});

				__switch(identity, a, y);
				return position = y;

			// handle player
			}, __player = function(file) {
				Petolio.loadJs('jquery/jquery.jplayer.min.js');

				var file = file.toLowerCase(),
					ext = file.split('.').pop(),
					media = {};

				// set media
				media[ext] = dash ? file : SITE_URL + file.substr(1);

				// load jplayer
				$("#jquery_jplayer_1").jPlayer({
					ready: function (event) {
						$(this).jPlayer("setMedia", media);
					},
					swfPath: SITE_URL + "swf",
					supplied: ext,
					wmode: "window"
				});

			// handle social
			}, __social = function(identity, d) {
				var x = data[d],
					params = {
						scope: dash ? dash[1] : 'po_files',
						label: dash ? '{ignore}' : '{direct}',
						id: dash ? dash[0] : x[0],
						url: '<a href="'+ ((url ? url : _url()) + (dash ? '' : '#aud/'+ x[0])) +'">{'+ (dash ? 'entries' : 'audios') +'}</a>',
						owner: dash ? dash[2] : x[2]
					};

		        Social.load('comments', $("#"+ identity), params);
		        Social.load('ratings', $("#"+ identity), params);
		        Social.load('subscriptions', $("#"+ identity), params);

			// open dialog
			}, __open = function(x) {
				if(Petolio.stopLoading() == true)
					return true;

				var identity = 'dialog-audio';
		    	$('<div id="'+ identity +'" title="'+ translate.view_audio +'" class="ui-state-highlight">'+
					'<div style="position: relative; margin: 8px 0px 8px 0px; width: 802px; overflow: hidden;">' +
						'<div style="margin: 0 auto 0 auto;" id="main_entity">'+
							player +
						'</div>'+
					'</div>'+
					'<div class="social" style="text-align: left; width: 500px; margin: 0 auto; position: relative;">'+
						'<div class="comments"><div style="height: 7px;"></div><div style="text-align: center; padding: 2px 5px; border: 1px solid #A5CC7D; background: #CEECB0;">'+ translate.load_social +'</div><div style="height: 7px;"></div></div>'+
						'<div style="position: absolute; top: 10px; right: 0px;">'+
							'<span class="subscriptions"></span>'+
							'<span class="ratings"></span>'+
						'</div>'+
					'</div>'+
				'</div>').dialog({
					resizable: false,
					modal: true,
					width: 825,
					position: ['center', 25],
					minHeight: 50,
					buttons: [{
						text: translate.close,
						click: function() {
							$(this).dialog("close");
						}
					}],
					close: function() {
						$("#"+ identity).remove();
						_trigger();
					},
					open: function() {
						// handle player
						__player(data[x.data[x.pos][1]][1]);

						// if there's more than 1 picture add gallery functionality
						if(x.total > 1)
			        		gallery(x, identity,
			        			// previous callback
			        			function() {
				        			__social(identity, __click(identity, 'prev'));

								// next callback
				        		}, function() {
				        			__social(identity, __click(identity, 'next'));
				        	});

				        // run by social plugins
						__social(identity, position);
					}
				});
			};

		// create video dialog
		},	_vid = function(x, y) {
			// comming from dashboard or hash or detail page
			if(isNaN(x)) {
				// if dashboard, we have data path and url
				var url = x.data('url');

				// external ? (dashboard)
				if(y == true) {
					var path = x.data('url'),
						dash = x.closest('div.entry').data('identity').split('|'),
						url = SITE_URL + 'dashboard/view/id/'+ dash[0];
				}

				// x is the file id
				x = x.attr('rel');
			}

			// show loading
			Petolio.showLoading();

			// run the ajax
	    	Petolio.ajax({
				url: 'imgsw/vid',
				type: 'post',
				data: {id: x, path: path ? paths.video.replace('{video}', path) : paths.video},
				cache: false,
				success: function (x) {
					// set local cache
					data = {};
					position = x.data[x.pos][1];
					$.each(x.data, function(i, v) {
						data[v[1]] = v;
					});

					Petolio.hideLoading();
					__open(x);
				}
			});

			// switch between videos
			var __switch = function(identity, a, y) {
				// update DOM
		        $("#"+ identity).dialog("option", "title", translate.view_video + ' - '+ translate.progress.replace('%1$s', a.indexOf(y) + 1).replace('%2$s', a.length));
				$('#main_entity').html($('<iframe width="640" height="360" frameborder="0" src="'+ data[y][1] +'?wmode=opaque" allowfullscreen="true"></iframe>').css({display: 'block'}));

			// handle on gallery click
			}, __click = function(identity, f) {
				var a = [];
				$.each(data, function(i, v){ a.push(i); });

				var x = a.indexOf(position),
					y = ImgSw[f]({data: a, pos: x});

				__switch(identity, a, y);
				return position = y;

			// handle social
			}, __social = function(identity, d) {
				var x = data[d],
					params = {
						scope: dash ? dash[1] : 'po_files',
						label: dash ? '{ignore}' : '{direct}',
						id: dash ? dash[0] : x[0],
						url: '<a href="'+ ((url ? url : _url()) + (dash ? '' : '#vid/'+ x[0])) +'">{'+ (dash ? 'entries' : 'videos') +'}</a>',
						owner: dash ? dash[2] : x[2]
					};

		        Social.load('comments', $("#"+ identity), params);
		        Social.load('ratings', $("#"+ identity), params);
		        Social.load('subscriptions', $("#"+ identity), params);

			// open dialog
			}, __open = function(x) {
				if(Petolio.stopLoading() == true)
					return true;

				var identity = 'dialog-video';
				$("#"+ identity).remove();
				$('<div id="'+ identity +'" title="'+ translate.view_video +'" class="ui-state-highlight">'+
					'<div style="margin: 8px 0px 8px 0px; position: relative; width: 642px; overflow: hidden;">'+
						'<div style="margin: 0 auto 0 auto; border: 1px solid #fff; background: black url(/images/ajax-loader-black.gif) center center no-repeat;" id="main_entity">'+
							'<iframe width="640" height="360" frameborder="0" src="'+ data[x.data[x.pos][1]][1] +'?wmode=opaque" allowfullscreen="true" style="display: block;"></iframe>'+
						'</div>'+
					'</div>'+
					'<div class="social" style="text-align: left; width: 500px; margin: 0 auto; position: relative;">'+
						'<div class="comments"><div style="height: 7px;"></div><div style="text-align: center; padding: 2px 5px; border: 1px solid #A5CC7D; background: #CEECB0;">'+ translate.load_social +'</div><div style="height: 7px;"></div></div>'+
						'<div style="position: absolute; top: 10px; right: 0px;">'+
							'<span class="subscriptions"></span>'+
							'<span class="ratings"></span>'+
						'</div>'+
					'</div>'+
				'</div>').dialog({
					resizable: false,
					modal: true,
					width: 665,
					position: ['center', 25],
					minHeight: 50,
					buttons: [{
						text: translate.close,
						click: function() {
							$(this).dialog("close");
						}
					}],
					close: function() {
						$("#"+ identity).remove();
						_trigger();
					},
					open: function() {
						// if there's more than 1 picture add gallery functionality
						if(x.total > 1)
			        		gallery(x, identity,
			        			// previous callback
			        			function() {
				        			__social(identity, __click(identity, 'prev'));

								// next callback
				        		}, function() {
				        			__social(identity, __click(identity, 'next'));
				        	});

				        // run by social plugins
						__social(identity, position);
					}
				});
			};

		// load from hash
		},	hash = function(d) {
			var h = window.location.hash.substring(1),
				r = h.match(/(img|vid|aud)\/(\d+)/),
				i = window.location.href;

			// valid hash?
			if(r == null)
				return;

			// valid id?
			if(isNaN(r[2]))
				return;

			// intercept and decline if request comes from dashboard
			if(i.search(/dashboard/i) != -1)
				return;

			// attempt to load based on hash
			return eval('_' + r[1] + '(r[2])');

		// get the correct url for social
		}, _url = function() {
			var $$ = frame ? window.microsite : document,
				url = $$.location.protocol + '//' + $$.location.hostname + $$.location.pathname;

			return url.replace('/iframe/true', '');

		// attach gallery functionality
		},	gallery = function(x, identity, p, n) {
			var t = $("#"+ identity).dialog("option", "title");
	        $("#"+ identity).dialog("option", "title", t + ' - '+ translate.progress.replace('%1$s', x.pos + 1).replace('%2$s', x.total));

	        // append the prev and next buttons
	        $('#main_entity').parent().append('<div id="dialog-prev" style="cursor: pointer; position: absolute; width: 100px; height: 260px; padding: 0px; margin-top: -130px; top: 50%; left: 0;">'+
	        		'<div style="position: absolute; top: 50%; right: 10px; margin-top: -40px; width: 78px; height: 78px; border: 1px solid #dddddd; background: white url(\'/images/prev.png\') center center no-repeat; background-color: rgba(255, 255, 255, 0.3);"></div>'+
				'</div>');
	        $('#main_entity').parent().append('<div id="dialog-next" style="cursor: pointer; position: absolute; width: 100px; height: 260px; padding: 0px; margin-top: -130px; top: 50%; right: 0;">'+
	        		'<div style="position: absolute; top: 50%; left: 10px; margin-top: -40px; width: 78px; height: 78px; border: 1px solid #dddddd; background: white url(\'/images/next.png\') center center no-repeat; background-color: rgba(255, 255, 255, 0.3);"></div>'+
				'</div>');

	        // chrome select fix
	        $("#dialog-prev, #dialog-next").bind("dragstart", _pdef).bind("selectstart", _pdef);

	        // on hover show, else hide
			var stop = {attr: function(){ return false; }};
			$("#main_entity").parent().mouseenter(function() {
				stop = $(this);
				$(this).find("#dialog-prev, #dialog-next").show();
			}).mouseleave(function() {
				$(this).find("#dialog-prev, #dialog-next").hide();
			});

			// automatically hide after 2 seconds
			window.setTimeout(function() {
				$("#dialog-prev, #dialog-next").each(function(s, i){
					var t = $(i).parent();
					if(stop.attr('rel') !== t.attr('rel'))
						$(i).hide();
				});
			}, 2000);

			// callbacks
	        $('#dialog-prev').click(function() {
	        	if(p) p.apply(this, Array.prototype.slice.call(arguments, 1));
		    });
	        $('#dialog-next').click(function() {
	        	if(n) n.apply(this, Array.prototype.slice.call(arguments, 1));
		    });

		// decide what this is based on url
		},	decide = function(d) {
			var x = d.attr('rel') == 'external' ? true : false;

			return eval('_' + d.attr('class') + '(d, x)');

		// imgsw constructor
		},	__construct = function(p, f) {
			frame = f;
			paths = p.paths;
			translate = p.translate;

			var $$ = function(e) {
				return f ? $("#frame").contents().find(e) : $(e);
			};

			$$("body").delegate('div.pictures span.img, div.pictures span.vid, div.pictures span.aud', 'click', function(e) {
				decide($(e.target));
			});

			hash();
		};

	// public
	return {
		init: __construct,
		next: next,
		prev: prev
	};
}();